//
//  GDLoopView.m
//  Gunterapple
//
//  Created by 热带雨林 on 2020/4/4.
//  Copyright © 2020 热带雨林. All rights reserved.
//

#import "GDLoopView.h"
#import "GDCollectionViewFlowLayout.h"
#import "GGAddtion.h"
#import "GDLoopCell.h"
#import "GDTimer.h"
static NSString *cellID = @"cellID";
@interface GDLoopView ()<UICollectionViewDelegate,UICollectionViewDataSource>
@property (nonatomic, weak) UICollectionView *collectionView;
@property (nonatomic, strong) NSArray *imageArray;
@property (nonatomic, weak) NSTimer *timer;
@property (nonatomic, strong) UIPageControl *pageControl;
@end

@implementation GDLoopView

//- (instancetype)initWithFrame:(CGRect)frame{
//    if(self = [super initWithFrame:frame]){
//        [self setUI];
//    }
//    return self;
//}

- (instancetype)initWithImageArray:(NSArray *)imageArray{
    if(self = [super init]){
        self.imageArray = imageArray;
        [self setUI];
    }
    return self;
}
- (void)setUI{
    
    //添加collectionView
    GDCollectionViewFlowLayout *layout = [[GDCollectionViewFlowLayout alloc]init];
//    UICollectionView *collectionView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:layout];
    UICollectionView *collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0,GDScreenW, 120) collectionViewLayout:layout];
    //因使用的就是自定义实例方法没有使用initWithFrame方法,以下方式设置约束无用，需要给出具体数值
//     UICollectionView *collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0,CGRectGetWidth(self.frame), CGRectGetHeight(self.frame)) collectionViewLayout:layout];
    self.collectionView = collectionView;
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self addSubview:self.collectionView];
    
    [self.collectionView registerClass:[GDLoopCell class] forCellWithReuseIdentifier:cellID];
    
    [self addSubview:self.pageControl];
    
    //回到主线程更新UI
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:self.imageArray.count inSection:0] atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
        //添加定时器
        [self addTimer];
    });
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.imageArray.count * 3;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    GDLoopCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellID forIndexPath:indexPath];
    cell.imageName = self.imageArray[indexPath.item % self.imageArray.count];
    return cell;
}
#pragma mark - 根据滚动的属性进行判断是否是存在手动拖动
//滚动完毕就会调用（如果不是人为拖拽scrollView导致滚动完毕，才会调用这个方法）
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView{
    //
//    [self scrollViewDidEndScrollingAnimation:scrollView];
    [self scrollViewDidEndDecelerating:scrollView];
}
//当滚动减速时调用
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    CGFloat offsetX = scrollView.contentOffset.x;
    NSInteger page = offsetX / scrollView.frame.size.width;
    //手指拖到了最左边
    if(page == 0){
        page = self.imageArray.count;
        self.collectionView.contentOffset = CGPointMake(page *scrollView.frame.size.width, 0);
    }else if (page == [self.collectionView numberOfItemsInSection:0] - 1){
        //手指拖到了最右边
        page = self.imageArray.count - 1;
        self.collectionView.contentOffset = CGPointMake(page * scrollView.frame.size.width, 0);
    }
    //设置当前页
    NSInteger currentPage = page % self.imageArray.count;
    self.pageControl.currentPage = currentPage;
    //手指滑动时删除掉了定时器
    [self addTimer];
}
//手指拖动时开始调用
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self removeTimer];
}
#pragma mark - 添加定时器
- (void)addTimer{
    if(self.timer) return;
    self.timer = [GDTimer scheduledTimerWithTimerInterval:1.5 withTarget:self withSelector:@selector(nextImage) withUserInfo:nil withRepeats:YES];
    //将timer添加到当前loop中
    /**
     不同于performSelecter，内部会创建一个timer加入到当前的runloop中
     */
    //添加的是伪模式，在手指滑动时也能执行
    [[NSRunLoop currentRunLoop]addTimer:self.timer forMode:NSRunLoopCommonModes];
    
}

#pragma mark - 移除定时器
- (void)removeTimer{
    [self.timer invalidate];
    self.timer = nil;
}
#pragma mark - 滚动到下一张的方法
- (void)nextImage{
    CGFloat offsetX = self.collectionView.contentOffset.x;

    //注意bounds与frame的区别
    //bounds是自己的 frame是相对于父控件的
    NSInteger page = offsetX / self.collectionView.frame.size.width;

    //滚动到下一页
    [self.collectionView setContentOffset:CGPointMake((page + 1) * self.bounds.size.width, 0) animated:YES];
}
#pragma mark - lazy
- (UIPageControl *)pageControl{
    if(!_pageControl){
        _pageControl = [[UIPageControl alloc]initWithFrame:CGRectMake(0, 120, 0, 30)];
        _pageControl.numberOfPages = self.imageArray.count;
        //设置选中与未选中的颜色
        _pageControl.pageIndicatorTintColor = [UIColor orangeColor];
        _pageControl.currentPageIndicatorTintColor = [UIColor purpleColor];
    }
    return _pageControl;
}
#pragma mark - 移除定时器
-(void)dealloc{
    [self removeTimer];
}
//- (void)layoutSubviews{
//    [super layoutSubviews];
////    self.collectionView.frame = self.bounds;
//}
@end
